﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using MyWeb.Data;
using MyWeb.Business;
using MyWeb.Common;

namespace MyWeb.Module.Shop
{
    public partial class GioHang : System.Web.UI.Page
    {
        static string ProductId = "";
        int quantity = 0;
        DataTable dtshopingcard;
        public static DataView dv;
        //sqldataprovide trong phan dathang
        SqlDataProvider sql = new SqlDataProvider();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.Page.RouteData.Values["Id"] != null)
            {
                ProductId = this.Page.RouteData.Values["Id"].ToString();
                Session["Id"] = ProductId;
            }


            if (!IsPostBack)
            {
                if (Session["quantity"] != null)
                {
                    quantity = Convert.ToInt32(Session["quantity"]);
                }
                else
                {
                    quantity = 1;
                }
                checksanpham();
                tongtien();
                thongtinkhach();

            }

        }
        protected void checksanpham()
        {
            if (Session["Id"] != null)
            {
                ProductId = Session["Id"].ToString();
                if (CheckProductID(ProductId) == true)
                {
                  
                    DataTable dt = new DataTable();
                    dt = (DataTable)Session["Cart"];
                    grvGioHang.DataSource = dt;
                    grvGioHang.DataBind();
                }
                else
                {
                    ShowCart();
                }

                if (Session["Cart"] == null)
                {
                    lblcheck.Text = "Chưa có sản phẩm";
                }
            }
            else
            {
                DataTable dt = new DataTable();
                dt = (DataTable)Session["Cart"];
                grvGioHang.DataSource = dt;
                grvGioHang.DataBind();
            }
        }
        protected void thongtinkhach()
        {
            if (Session["CusId"] == null)
            {
                tongtien();
            }
            if (Session["CusId"] != null)
            {
                List<Data.Custormer> list = CustormerService.Custormer_GetById(Session["CusId"].ToString());
                if (list.Count > 0)
                {
                    txtName.Text = list[0].Name;
                    txtDiaChiNM.Text = list[0].Address;
                    txtDienthoaiNM.Text = list[0].Phone;
                    txtEmailNM.Text = list[0].Email;
                    txtrequest.Text = list[0].Detail;
                }
            }
        }
        protected string Formatmoney(string money)
        {
            string tien = "";
            try
            {
                tien = "" + Double.Parse(money).ToString("#,000") + " VNĐ";
            }
            catch
            {
                return tien = "";
            }
            return tien;
        }
        private void ShowCart()
        {
            List<Data.Product> list = new List<Data.Product>();
            if (Session["Cart"] == null)
            {
                dtshopingcard = new DataTable();
                dtshopingcard.Columns.Add("Id", typeof(String));
                dtshopingcard.Columns.Add("Name", typeof(String));
                dtshopingcard.Columns.Add("Price", typeof(String));
                dtshopingcard.Columns.Add("quantity", typeof(String));
                dtshopingcard.Columns.Add("TotalPrice", typeof(String));
                DataRow rows = dtshopingcard.NewRow();
                list = ProductService.Product_GetById(ProductId);
                rows["Id"] = list[0].Id;
                rows["Name"] = list[0].Name;
                rows["Price"] = list[0].PriceNew;
                rows["quantity"] = quantity;
                rows["TotalPrice"] = (Convert.ToInt32(list[0].PriceNew) * quantity).ToString();
                dtshopingcard.Rows.Add(rows);
            }
            else
            {
                dtshopingcard = (DataTable)Session["Cart"];
                DataRow rows = dtshopingcard.NewRow();
                list = ProductService.Product_GetById(ProductId);
                rows["Id"] = list[0].Id;
                rows["Name"] = list[0].Name;
                rows["Price"] = list[0].PriceNew;
                rows["quantity"] = quantity;
                rows["TotalPrice"] = (Convert.ToInt32(list[0].PriceNew) * quantity).ToString();
                dtshopingcard.Rows.Add(rows);
            }
            Session["Cart"] = dtshopingcard;
            DataTable dt = (DataTable)Session["Cart"];
            grvGioHang.DataSource = dt;
            grvGioHang.DataBind();
        }
        bool CheckProductID(string proid)
        {
            bool flag = false;
            if (Session["Cart"] != null)
            {
                DataTable dtcheck = (DataTable)Session["Cart"];
                if (dtcheck.Rows.Count > 0)
                {
                    for (int i = 0; i < dtcheck.Rows.Count; i++)
                    {
                        if (dtcheck.Rows[i]["Id"].Equals(proid))
                        {
                            flag = true;
                        }
                    }
                }
                else
                {
                    flag = false;

                }
            }
            return flag;
        }
        protected void grvGioHang_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strA = e.CommandArgument.ToString();
            switch (e.CommandName)
            {
                case "Update":
                    Label lblProductId;
                    string lbtTotal;
                    for (int i = 0; i < grvGioHang.Rows.Count; i++)
                    {
                        lblProductId = (Label)grvGioHang.Rows[i].FindControl("lblproductid");
                        if (lblProductId.Text.Trim().Equals(strA))
                        {
                            Label lblprice = (Label)grvGioHang.Rows[i].FindControl("lblGia");
                            TextBox quantitytext = (TextBox)grvGioHang.Rows[i].FindControl("txtSoLuong");
                            //lbtTotal = (Label)grvGioHang.Rows[i].FindControl("lblTongGia");
                            string nu = quantitytext.Text;
                            string gia = lblprice.Text.Replace("VND", "");
                            lbtTotal = (Int32.Parse(gia) * Int32.Parse(nu)).ToString();
                            //lblprice.Text = lblprice.Text + "VND";
                            Cart_UpdateNumber((DataTable)Session["Cart"], strA, Int32.Parse(nu), lbtTotal);
                        }
                    }
                    Response.Redirect(Request.Url.LocalPath.ToString());
                    break;
                case "Delete":
                    DataTable dt1 = (DataTable)Session["Cart"];
                    if (dt1.Rows.Count > 0)
                    {
                        for (int i = 0; i < dt1.Rows.Count; i++)
                        {
                            if (dt1.Rows[i]["Id"].ToString().Equals(strA))
                            {

                                dt1.Rows[i].Delete();
                                Session.Remove("Id");
                            }
                        }
                        if (dt1.Rows.Count < 1)
                        {
                            Session.Remove("Cart");
                            Session.Remove("Id");
                        }
                    }
                    else
                    {
                        Session.Remove("Cart");
                    }
                    Session["Cart"] = dt1;
                    //grvGioHang.DataSource = dt1;
                    //grvGioHang.DataBind();
                    Response.Redirect(Request.Url.LocalPath.ToString());
                    break;
            }
        }
        private void Cart_UpdateNumber(DataTable cartdetail, string proid, int inumber, string Total)
        {
            if (cartdetail.Rows.Count > 0)
            {
                for (int j = 0; j < cartdetail.Rows.Count; j++)
                {
                    if (cartdetail.Rows[j]["Id"].ToString().Equals(proid))
                    {
                        cartdetail.Rows[j]["quantity"] = inumber;
                        cartdetail.Rows[j]["TotalPrice"] = Total;
                        break;
                    }
                }
            }
        }
        protected void tongtien()
        {
            int totalprice = 0;
            for (int i = 0; i < grvGioHang.Rows.Count; i++)
            {
                Label lbltotalprice = (Label)grvGioHang.Rows[i].FindControl("lblTongGia");
                lbltotalprice.Text = lbltotalprice.Text.Replace("VND", "");
                totalprice += Convert.ToInt32(lbltotalprice.Text);
            }
            lblTongTien.Text = "Tổng tiền: " + "" + Formatmoney(totalprice.ToString()) + "";
        }

        protected void btndathang_Click(object sender, EventArgs e)
        {


            if (Session["Id"] == null)
            {
                lblcheck.Text = "Chưa Có Sản Phẩm Nào";
            }
            else
            {
                int sstotalprice = 0;
                for (int i = 0; i < grvGioHang.Rows.Count; i++)
                {
                    Label lbttotalprice1 = (Label)grvGioHang.Rows[i].FindControl("lblTongGia");
                    lbttotalprice1.Text = lbttotalprice1.Text.Replace("VND", "");
                    sstotalprice += Int32.Parse(lbttotalprice1.Text);
                }
                Session["TotalPrice"] = sstotalprice.ToString();
                ddlthanhtoan.Items.Clear();
                pncustomer.Visible = true;
                ddlthanhtoan.Items.Add(new ListItem("Chọn hình thức thanh toán", ""));
                ddlthanhtoan.Items.Add(new ListItem("Chuyển khoản qua thẻ", "Chuyển khoản qua thẻ"));
                ddlthanhtoan.Items.Add(new ListItem("Trực tiếp tại công ty", "Trực tiếp tại công ty"));


            }
            //if (Session["CusId"] == null)
            //{
            //    lblcheck.Text = "Bản Phải Đăng Nhập Để Mua Hàng";
            //    pncustomer.Visible = false;
            //}
        }

        protected void lblttkh_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                if (Session["CusId"] != null)
                {
                    Data.Custormer obj = new Data.Custormer();
                    obj.Id = Session["CusId"].ToString();
                    obj.Username = Session["Username"].ToString();
                    obj.Password = Session["Password"].ToString();
                    obj.Name = txtName.Text;
                    obj.Address = txtDiaChiNM.Text;
                    obj.Phone = txtDienthoaiNM.Text;
                    obj.Email = txtEmailNM.Text;
                    obj.Detail = txtrequest.Text;

                    CustormerService.Custormer_Update(obj);
                    if (Session["TotalPrice"] != null)
                    {
                        Data.Bill objOrder = new Data.Bill();
                        objOrder.CustormerId = Session["CusId"].ToString();
                        objOrder.Totalmoney = Session["TotalPrice"].ToString();
                        objOrder.Datesend = DateTime.Now.ToShortDateString();
                        objOrder.DateReceive = DateTime.Now.ToShortDateString();
                        objOrder.Name = txtName.Text;
                        objOrder.Request = txtrequest.Text;
                        objOrder.Active = "0";
                        BillService.Bill_Insert(objOrder);
                    }

                    string BillIds = sql.MaxId("Bill", "Id");
                    DataTable dt = new DataTable();
                    dt = (DataTable)Session["Cart"];
                    if (dt.Rows.Count > 0)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            List<Data.Product> list = ProductService.Product_GetById(dt.Rows[i]["Id"].ToString());
                            Data.BillDetail objDetail = new Data.BillDetail();
                            objDetail.BillId = BillIds;
                            objDetail.ProductId = list[0].Id;
                            objDetail.Price = list[0].PriceOld;
                            objDetail.Quantity = dt.Rows[i]["quantity"].ToString();
                            objDetail.Total = dt.Rows[i]["TotalPrice"].ToString();

                            BillDetailService.BillDetail_Insert(objDetail);
                        }
                    }
                    pnthanhcong.Visible = true;
                    pncustomer.Visible = false;
                }
                else if (Session["CusId"] == null)
                {
                    Data.Custormer obj = new Data.Custormer();
                    obj.Id = "";
                    obj.Username = "";
                    obj.Password = "";
                    obj.Name = txtName.Text;
                    obj.Address = txtDiaChiNM.Text;
                    obj.Phone = txtDienthoaiNM.Text;
                    obj.Email = txtEmailNM.Text;
                    obj.Detail = txtrequest.Text;
                    obj.Status = ddlthanhtoan.SelectedValue;
                    CustormerService.Custormer_Insert(obj);
                    if (Session["TotalPrice"] != null)
                    {
                        Data.Bill objOrder = new Data.Bill();
                        //SqlDataProvider sql = new SqlDataProvider();
                        //lấy Id lớn nhất vừa nhập vào
                        string CustormerId = sql.MaxId("Custormer", "Id");
                        objOrder.CustormerId = CustormerId;
                        objOrder.Totalmoney = Session["TotalPrice"].ToString();
                        objOrder.Datesend = DateTime.Now.ToShortDateString();
                        objOrder.DateReceive = DateTime.Now.ToShortDateString();
                        objOrder.Name = txtName.Text;
                        objOrder.Request = txtrequest.Text;
                        objOrder.Active = "0";

                        BillService.Bill_Insert(objOrder);
                    }
                    string BillIds = sql.MaxId("Bill", "Id");
                    DataTable dt = new DataTable();
                    if (Session["Cart"] != null)
                    {


                        dt = (DataTable)Session["Cart"];
                        if (dt.Rows.Count > 0)
                        {
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                List<Data.Product> list = ProductService.Product_GetById(dt.Rows[i]["Id"].ToString());
                                Data.BillDetail objDetail = new Data.BillDetail();
                                objDetail.BillId = BillIds;
                                objDetail.ProductId = list[0].Id;
                                objDetail.Price = list[0].PriceOld;
                                objDetail.Quantity = dt.Rows[i]["quantity"].ToString();
                                objDetail.Total = dt.Rows[i]["TotalPrice"].ToString();

                                BillDetailService.BillDetail_Insert(objDetail);
                            }
                        }
                    }
                    pnthanhcong.Visible = true;
                    pncustomer.Visible = false;
                    pnView.Visible = false;
                    resetcontrol();                 
                }
            }
        }

        protected void resetcontrol()
        {
            txtDiaChiNM.Text = "";
            txtName.Text = "";
            Session["Cart"] = null;
            Session["TotalPrice"] = null;
        }
        protected void btnmuatiep_Click(object sender, EventArgs e)
        {
            Response.Redirect("/Default.aspx");
        }

    }
}